package cn.aihongbo.kmp.base.vm

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.launch

open class HViewModel : ViewModel() {
    val _isLoading = mutableStateOf(false)
    val isLoading: State<Boolean> = _isLoading

    val _error = mutableStateOf<String?>(null)
    val error: State<String?> = _error

    fun net(block: (suspend () -> Unit)) {
        viewModelScope.launch(Dispatchers.IO) {
            _isLoading.value = true
            try {
                block()
            } catch (e: Exception) {
                _error.value = e.message
                println("ERROR START====================================================================================")
                println(e.message)
                println("ERROR END====================================================================================")
            } finally {
                _isLoading.value = false
            }
        }
    }
}